# -*- coding: utf-8 -*-
"""xmonitor.py 网站定时监测
定时访问CIV论坛，新增帖子数大于5或发生网络异常则发邮件示警
"""
from urllib.request import urlopen, Request
import re
import time
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from email.utils import formataddr
import json
with open("settings.json") as f:  # 配置文件
    settings = json.load(f)
mail_sender = settings["mail_sender"]
mail_receiver = settings["mail_receiver"]
smtp_host = settings["smtp_host"]
smtp_user = settings["smtp_user"]
smtp_pass = settings["smtp_pass"]
site = "CIV论坛"
url = "http://www.civclub.net/bbs"
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:61.0) \
           Gecko/20100101 Firefox/61.0'}


def mail(title, content):
    """发送邮件
    """
    msg = MIMEText(content, "plain", "utf-8")
    msg["From"] = formataddr(["监测员", mail_sender])
    msg["To"] = formataddr(["管理员", mail_receiver])
    msg["Subject"] = Header(f"{site}：{title}", "utf-8")
    try:
        smtp = smtplib.SMTP(smtp_host)
        smtp.ehlo()
        smtp.starttls()
        smtp.login(smtp_user, smtp_pass)
        smtp.sendmail(mail_sender, mail_receiver, msg.as_string())
        print("邮件发送成功")
    except Exception as e:
        print(f"邮件发送失败：{repr(e)}")


def main():
    """每小时获取新增帖数，大于5或发生网络异常则发邮件示警
    """
    posts = 0  # 发帖数
    while True:
        print(f"检查网站：{url}")
        try:
            req = Request(url=url, headers=headers)
            html = urlopen(req).read().decode("gbk")
            match = re.search(r'今日: <em>(\d+?)</em>', html)
            newposts = int(match.group(1))
            increase = newposts - posts
            if increase > 5:
                mail("发帖量大", f"近一小时新增{increase}个帖子")
            posts = newposts
        except Exception as e:
            mail("异常错误", repr(e))
        print("进入休眠……")
        for _ in range(3600):  # 休眠一小时
            time.sleep(1)


if __name__ == "__main__":
    main()
